import requests
import time
import hmac
import hashlib
import base64
import json

# 替换为你的飞书 Webhook 地址和 Secret
WEBHOOK_URL = 'https://open.feishu.cn/open-apis/bot/v2/hook/4a100e0d-47e8-4632-87f5-0545978822ca'
SECRET = '68aLtJoTosSRbcyAXbCsZ'

# 文本消息

def make_text_msg(content):
    text_msg = {
        "msg_type": "text",
        "content": {"text": content}
    }
    return text_msg


# 富文本消息（含@用户）
def make_rich_msg(content):
    post_msg = {
        "msg_type": "post",
        "content": {
            "post": {
                "zh_cn": {
                    "title": "公告",
                    "content": [[
                        {"tag": "text", "text": content},
                        # {"tag": "at", "user_id": "ou_123456"}
                    ]]
                }
            }
        }
    }
    return post_msg

# 消息卡片
def make_card_msg(content: str):  # 明确要求content为字符串
    card_msg = {
        "msg_type": "interactive",
        "card": {
            "header": {
                "title": {"tag": "plain_text", "content": "任务提醒"},  # 修正title结构
                "template": "red"
            },
            "elements": [{
                "tag": "div",
                "text": {
                    "content": str(content),  # 强制转换为字符串
                    "tag": "lark_md"
                }
            }]
        }
    }
    return card_msg


def gen_sign(timestamp, secret):
    # 拼接timestamp和secret
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
    # 对结果进行base64处理
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign
def send_feishu_text(content):
    timestamp = str(int(time.time()))  # 秒级时间戳，必须是字符串
    sign = gen_sign(SECRET, timestamp)

    payload = {
        "timestamp": timestamp,
        # "sign": sign,
    }
    content = make_text_msg(content)
    payload.update(content)
    headers = {
        'Content-Type': 'application/json'
    }

    # 调试信息
    # print("Payload:\n", json.dumps(payload, indent=2))

    response = requests.post(WEBHOOK_URL, headers=headers, data=json.dumps(payload))
    # print("Status:", response.status_code)
    # print("Response:", response.text)

if __name__ == "__main__":
    # send_feishu_text("测试消息：Python 机器人 + 签名成功 ✅")
    send_feishu_text(make_card_msg("xxxx"))
